// 获取应用实例
const app = getApp();
const departmentArr = ['综合办', '交接处', '工程部', '已完结'];
Page({
    data: {
        // 18591990935 
        productInfo: [],
        dataUrlArr: [],
        select: true,
        name: '', // 工单人姓名 
        tel: '', // 电话
        money: '', // 装修数量
        typeName: '',
        days: '0',
        reviewTel: '', // 复核电话
        affiliatedName: '',
        sign1: '0',
        sign2: '0',
        sign3: '0',
        explains: '', // 说明
        isDelivery: '',
        isPlacement: '',
        total: 0,
        picture: '', // 照片最多三张多个逗号隔开
        attachment: [],
        type: '',
        reasons: '', // 审核原因
        id: '',
        dpId: 0,
        list: [],
        isOpen: false,
        detailShow: false,
        detailItem: {},
        isUpload: false,
        fileLength: 0,
        share: false,
        loading: false,
        plaReason: '输入审核原因',
        admin: 0,
        subAdmin: 0,
        isCaiwu: false,
        isOpen1: false,
        evaluateData: [],
        status: '综合办',
        collectionList: [],
        changeList: [],
        allMoneyData: {},
        placementTime: '',
        placementUserName: '',
        deliveryTime: '',
        deliveryUserName: '',
        fan: '', // 开扇数量
        door: '', // 开门数量
        tube: '', // 方管数量
        inversion: '', // 内倒数量
        transfer: '', // 转角数量
        window: '', // 纱窗数量
        packName: '',
        brandName: '',
        materialName: '',
        thicknessName: '',
        openName: '',
        content: '',
        title: '',
        userId: '',
        telphone: '15229883888',
        paymentShow: false
    },
    onLoad(option) {
        this.setData({
            id: option.id,
            share: option?.share,
            dpId: option.dpId,
            admin: wx.getStorageSync('admin'),
            subAdmin: wx.getStorageSync('subAdmin'),
            userId: wx.getStorageSync('userId'),
            // status: departmentArr[option.dpId]
        });
        this.getDepartment(option.id);
        this.getPrivery();
    },
    onReady() {
    },
    onShow() {
        this.getDepartmentList();
        this.getEvaluateList();
        this.getChangeData();
        this.getReceiptsData();
        this.getAllMoney();
        this.getphone();
    },
    //刷新
    onPullDownRefresh() {

    },

    getDepartmentList() {
        wx.request({
            url: `${app.globalData.baseUrl}/api/finance/getUserDept`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    const deptIds = [];
                    res?.data?.data?.forEach(item => {
                        deptIds.push(item.deptId);
                    });
                    if (deptIds.indexOf(3) > -1) {
                        this.setData({ isCaiwu: true });
                    } else {
                        this.setData({ isCaiwu: false });
                    }
                }
            }
        })
    },

    removeImage(e) {
        const arrReally = this.data.dataUrlArr;
        const index = e.currentTarget.dataset.index
        arrReally.splice(index, 1);
        this.setData({ dataUrlArr: arrReally })
    },

    // 审核原因
    handReasonsChange(e) {
        this.setData({
            reasons: e.detail.value
        })
    },
    reject() {
        if ((this.data.dpId != 3 && this.data.isPlacement == 1) || (this.data.dpId == 3 && this.data.isDelivery == 1)) {
            const that = this;
            wx.showModal({
                content: that.data.dpId != 3 && that.data.isPlacement == 1 ? '请再次确认所有问题都已处理？是否交接下一部门' : '此单已交付！是否违规操作',
                title: that.data.dpId != 3 && that.data.isPlacement == 1 ? '提示' : '警告',
                cancelText: '关闭',
                complete: (res) => {
                    if (res.cancel) {
                        console.log('取消')
                    }

                    if (res.confirm) {
                        that.submit(9);
                    }
                }
            });
        } else {
            this.submit(9);
        }
    },
    delete() {
        const that = this;
        wx.showModal({
            content: '确认删除吗？',
            success: function (sm) {
                if (sm.confirm) {
                    wx.request({
                        url: `${app.globalData.baseUrl}/api/finance/del?id=${that.data.id}`,
                        method: "GET",
                        header: {
                            'token': wx.getStorageSync('token'),
                            "Content-Type": "application/json"
                        },
                        data: {},
                        success: (res) => {
                            if (res.data.code == 0) {
                                wx.showToast({
                                    title: '操作成功',
                                });
                                wx.navigateBack({
                                    id: that.data.dpId,
                                });
                            }
                        }
                    })
                } else {
                    console.log('用户点击取消');
                }
            }
        })
    },
    adopt() {
        if (this.data.isPlacement == 1) {
            const that = this;
            wx.showModal({
                title: '提示',
                cancelText: '关闭',
                content: '请再次确认所有问题都已处理？是否交接下一部门',
                complete: (res) => {
                    if (res.cancel) {
                        console.log('取消操作')
                    }

                    if (res.confirm) {
                        that.submit(1);
                    }
                }
            })
        } else {
            this.submit(1);
        }
    },
    // 获取财务工单详情
    getDepartment(id) {
        wx.request({
            url: `${app.globalData.baseUrl}/api/finance/selById`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            data: {
                id: id,
            },
            success: (res) => {
                if (res.data.code == 0) {
                    if (res.data.data.length != 0) {
                        res.data.data.list.forEach((item, index) => {
                            item.index = res.data.data.list?.length - index;
                        });

                        this.setData({
                            name: res.data.data.name,
                            tel: res.data.data.tel,
                            money: res.data.data.money,
                            typeName: res.data.data.typeName,
                            days: res.data.data.days,
                            reviewTel: res.data.data.reviewTel,
                            total: res.data.data.total,
                            affiliatedName: res.data.data.affiliatedName,
                            attachment: res.data.data.attachment ? res.data.data.attachment.split(',') : [],
                            type: res.data.data.type,
                            explains: res.data.data.explains,
                            isDelivery: res.data.data.isDelivery,
                            isPlacement: res.data.data.isPlacement,
                            picture: res.data.data.picture,
                            productInfo: res.data.data.picture.split(','),
                            list: res.data.data.list,
                            sign1: res.data.data.sign1,
                            sign2: res.data.data.sign2,
                            sign3: res.data.data.sign3,
                            placementTime: res.data.data.placementTime,
                            placementUserName: res.data.data.placementUserName,
                            deliveryTime: res.data.data.deliveryTime,
                            deliveryUserName: res.data.data.deliveryUserName,
                            fan: res.data.data.fan, // 开扇数量
                            door: res.data.data.door, // 开门数量
                            tube: res.data.data.tube, // 方管数量
                            inversion: res.data.data.inversion, // 内倒数量
                            transfer: res.data.data.transfer, // 转角数量
                            window: res.data.data.window, // 纱窗数量
                            packName: res.data.data.packName,
                            brandName: res.data.data.brandName,
                            materialName: res.data.data.materialName,
                            thicknessName: res.data.data.thicknessName,
                            openName: res.data.data.openName,
                            status: departmentArr[res.data.data.status]
                        })
                    }
                }
            }
        })
    },
    //预览图片，放大预览
    preview(e) {
        let currentUrl = this.data.productInfo;
        let index = e.currentTarget.dataset.index;
        wx.previewImage({
            current: currentUrl[index], // 当前显示图片的http链接
            urls: this.data.productInfo // 需要预览的图片http链接列表
        })
    },
    //预览图片，放大预览
    preview_1(e) {
        let currentUrl = this.data.dataUrlArr;
        let index_1 = e.currentTarget.dataset.index;
        wx.previewImage({
            current: currentUrl[index_1], // 当前显示图片的http链接
            urls: this.data.dataUrlArr // 需要预览的图片http链接列表
        })
    },
    // 审核状态 1--通过 9--驳回
    submit(examineStatus) {
        if (this.data.reasons == "") {
            wx.showToast({
                title: '请输入审核原因',
                icon: "none"
            })
        } else if (this.data.dataUrlArr.length == 0) {
            wx.showToast({
                title: '请上传审核图片',
                icon: "none"
            })
        } else if (this.data.dataUrlArr && this.data.dataUrlArr.length > 9) {
            wx.showToast({
                title: '最多上传9张图片',
                icon: "none"
            })
        } else {
            let _that = this;
            let photoStr = this.data.dataUrlArr && this.data.dataUrlArr.join(",");
            wx.showLoading();
            this.setData({ loading: true });
            wx.request({
                url: `${app.globalData.baseUrl}/api/finance/examine`,
                method: "POST",
                data: {
                    financeId: Number(_that.data.id),
                    status: examineStatus,
                    reasons: _that.data.reasons,
                    picture: photoStr,// _that.data.picture 
                },
                header: {
                    "Content-Type": "application/json",
                    'token': wx.getStorageSync('token'),
                },
                success: (res) => {
                    if (res.data.code == 0) {
                        _that.updateStatus(examineStatus);
                        wx.showToast({
                            title: res.data.msg || '报错啦！',
                            duration: 2000
                        });
                    } else if (res.data.code == 500) {
                        wx.showToast({
                            title: res.data.msg || '报错啦！',
                            icon: 'error', //当icon：'none'时，没有图标 只有文字
                            duration: 2000
                        })
                    }
                    else {
                        wx.showToast({
                            title: '系统错误，请重新登录',
                        })
                    }
                },
                complete: () => {
                    wx.hideLoading();
                    _that.setData({ loading: false });
                }

            })
        }
    },
    extractNumbersFromString(str) {
        let numbers = [];
        if (str.indexOf('】') > -1) {
            const arr = str.split('】');
            if (arr.length > 1) {
                numbers = arr[arr.length - 1].match(/\d+/g);
            }
        } else if (str.indexOf(']') > -1) {
            const arr = str.split(']');
            if (arr.length > 1) {
                numbers = arr[arr.length - 1].match(/\d+/g);
            }
        } else {
            numbers = str.match(/\d+/g);
        }
        return numbers;
    },
    tell() {
        const arr = this.extractNumbersFromString(this.data.tel);
        console.log(arr);
        if (arr && arr.length > 0) {
            wx.makePhoneCall({
                phoneNumber: arr[arr.length - 1],
                success() {
                },
            })
        }
    },
    tellcover() {
        const arr = this.extractNumbersFromString(this.data.reviewTel);
        console.log(arr);
        if (arr && arr.length > 0) {
            wx.makePhoneCall({
                phoneNumber: arr[arr.length - 1],
                success() {
                },
            })
        }
    },

    /**
       * 用户点击右上角分享
       */
    onShareAppMessage: function () {
        return {
            title: `工单详情 （发起距今${this.data.days}天）`,
            path: `/pages/financialreview/index?id=${this.data.id}&dpId=${this.data.dpId}&share=true`
        }
    },
    panel(e) {
        this.setData({
            isOpen: !this.data.isOpen
        })
    },
    viewDetail(e) {
        let detailItem = e.currentTarget.dataset.viewitem;
        detailItem.picture = detailItem.picture ? detailItem.picture.split(',') : [];
        this.setData({ detailShow: true, detailItem, plaReason: '', });
    },
    detialHide() {
        this.setData({ detailShow: false, plaReason: '输入审核原因', });
    },
    preview_5(e) {
        const currentUrl = this.data.detailItem.picture;
        const idex = e.currentTarget.dataset.idex;
        wx.previewImage({
            current: currentUrl[idex], // 当前显示图片的http链接
            urls: [...currentUrl] // 需要预览的图片http链接列表
        })
    },
    uploadOpen: function (e) {
        this.setData({
            isUpload: true,
            fileLength: this.data.dataUrlArr.length,
            plaReason: '',
        });
    },
    
    download(e) {
      const that = this;
      wx.getSystemInfo({
        success: function(result) {
          if (result.platform === 'ios' || result.platform === 'android') {
            that.saveMobile(e.currentTarget.dataset.url);
          } else if (result.platform === 'windows' || result.platform === 'mac') {
            that.savePc(e.currentTarget.dataset.url);
          }
        }
      });
    },

    savePc(url) {
      wx.request({
        url: url,
        responseType: 'arraybuffer', // 设置响应类型为arraybuffer以接收二进制数据
        success: (res) => {
          // 获取文件名
          const fileName = url.split('/').pop();
       
          // 写入文件
          wx.getFileSystemManager().writeFile({
            filePath: wx.env.USER_DATA_PATH + '/' + fileName, // 指定要写入的文件路径
            data: res.data, // 文件内容
            encoding: 'binary', // 指定文件编码
            success: (writeRes) => {
              console.log('文件保存成功', writeRes);
              // 这里可以调用wx.saveFileToDisk将文件保存到用户电脑
              wx.saveFileToDisk({
                filePath: wx.env.USER_DATA_PATH + '/' + fileName,
                success: (saveRes) => {
                  console.log('文件保存到电脑成功', saveRes);
                },
                fail: (error) => {
                  console.error('文件保存到电脑失败', error);
                }
              });
            },
            fail: (error) => {
              console.error('文件保存失败', error);
            }
          });
        },
        fail: (error) => {
          console.error('文件下载失败', error);
        }
      });
    },
  
    saveMobile(url) {
      console.log(url, 'mobile')
      wx.downloadFile({
        url,
        success(res) {
          if (res.statusCode === 200) {
            console.log(res.tempFilePath)
            wx.openDocument({
              filePath: res.tempFilePath,
              showMenu: true
            });
          }
        }
      })
    },
    copyText(e) {
      wx.setClipboardData({
        data: e.currentTarget.dataset.url,
        success: function (res) {
          wx.showToast({
            title: '复制成功',
          });
        }
      });
    },
    uploadClose: function () {
        this.setData({
            isUpload: false,
            plaReason: '输入审核原因',
        });
    },
    receivingData: async function (val) {
        this.setData({
            dataUrlArr: [...this.data.dataUrlArr, val.detail]
        });
    },
    // TOO 评价页面
    toEvaluate() {
        wx.navigateTo({
          url: `/pages/evaluate/index?id=` + this.data.id
        })
    },

    toLogistics() {
      wx.navigateTo({
        url: `/pages/logistics/index?id=` + this.data.id
      })
    },

    toPayment() {
      this.setData({ paymentShow: true });
    },

    canelConfimPay() {
      this.setData({ paymentShow: false });
    },

    confimPay() {
      this.setData({ paymentShow: false });
      const payCodeUrl = 'https://repair.zhaishu.store/profile/upload/2025/10/03/d50436eb-30e7-411c-beea-2b7e5308d48f.jpg'
      wx.previewImage({
        current: payCodeUrl,
        urls: [payCodeUrl]
      })
    },

    evaluateOpen() {
        this.setData({ isOpen1: !this.data.isOpen1 });
    },

    preview_4(e) {
        const currentUrl = this.data.evaluateData;
        const index = e.currentTarget.dataset.index;
        const idex = e.currentTarget.dataset.idex;
        wx.previewImage({
            current: currentUrl[index].picture[idex], // 当前显示图片的http链接
            urls: [...currentUrl[index].picture] // 需要预览的图片http链接列表
        })
    },

    getEvaluateList() {
        wx.request({
            url: `${app.globalData.baseUrl}/api/notice/selCommentList?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                  res.data.rows?.forEach((item, index) => {
                    item.picture = item.picture ? item.picture.split(',') : [];
                    item.index = res.data.rows.length - index;
                  })
                  this.setData({
                      evaluateData: res.data.rows
                  })
                }
            }
        })
    },
    updateStatus(id) {
        const that = this;
        const data = {
            id: that.data.id,
            isDelivery: 0,
            isPlacement: 0,
        };
        if (id == 9 && that.data.dpId == 1) data.sign1 = '0';
        if (id == 9 && that.data.dpId == 3) { data.sign3 = '0'; data.sign2 = '0';}
        wx.request({
            url: `${app.globalData.baseUrl}/api/finance/update`,
            method: "POST",
            data: data,
            header: {
                "Content-Type": "application/json",
                'token': wx.getStorageSync('token'),
            },
            success: function (res) {
                if (res.data.code == 0) {
                    wx.navigateBack({
                        id: that.data.dpId,
                    });
                } else {
                    wx.showToast({
                        title: res.data.msg || '系统异常',
                    })
                }
            },
            fail() {
                wx.showToast({
                    title: '出错啦！',
                    icon: 'error',
                    duration: 2000
                })
            }
        })
    },
    getChangeData(val) {
        wx.request({
            url: `${app.globalData.baseUrl}/api/classify/selChangeList?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    res.data.rows.forEach((item, index) => {
                        item.index = res.data.rows?.length - index;
                    });
                    this.setData({ changeList: res.data.rows });
                    if(val) this.getAllMoney();
                }
            }
        })
    },
    getReceiptsData(val) {
        wx.request({
            url: `${app.globalData.baseUrl}/api/classify/selCollectionList?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    res.data.rows.forEach((item, index) => {
                        item.index = res.data.rows?.length - index;
                    });
                    this.setData({ collectionList: res.data.rows });
                    if(val) this.getAllMoney();
                }
            }
        })
    },

    getAllMoney() {
        wx.request({
            url: `${app.globalData.baseUrl}/api/classify/selFinanceTotal?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    const obj = res.data.data;
                    obj.balanceTotal = parseFloat(res.data.data.changeTotal) - parseFloat(res.data.data.collectionTotal);
                    this.setData({ allMoneyData: obj });
                }
            }
        })
    },
    agreement() {
      this.setData({ agreementShow: true });
    },
  
    closeModal() {
      this.setData({ agreementShow: false });
    },

    getPrivery() {
      wx.request({
        url: `${app.globalData.baseUrl}/api/memo/sekByRuleId?id=2`,
        method: "GET",
        header: {
          'token': wx.getStorageSync('token'),
          "Content-Type": "application/json"
        },
        success: (res) => {
          if (res.data.code == 0) {
            this.setData({ 
              content: res.data.data.content,
              title: res.data.data.title
            });
          }
        }
      })
    },

    getphone() {
      wx.request({
        url: `${app.globalData.baseUrl}/api/login/getContact`,
        method: "GET",
        header: {
          'token': wx.getStorageSync('token'),
          "Content-Type": "application/json"
        },
        success: (res) => {
          let that = this;
          if (res.data.code == 0 && res.data.data.length) {
            that.setData({ telphone: res.data.data[0].tel })
          }
        }
      })
    },

    isPlacementChange(e) {
      if (this.data.sign1 != 1) {
        wx.showModal({
          title: '提示',
          content: '工单未审核,请联系管理员授权，否则不能进展！',
          cancelText: '马上联系',
          confirmText: '关闭',
          complete: (res) => {
            if (res.confirm) {}
            if (res.cancel) {
              wx.makePhoneCall({
                phoneNumber: this.data.telphone,
                success() {
                },
              });
            }
          }
        })
        return;
      }
      const that = this;
      wx.showModal({
        content: e.detail ? '确定我来处理！工单将不再展示给外人！只属于勾选人！请你用心维护好本次服务！' : '确定取消我来处理？',
        cancelText: '关闭',
        success: function (sm) {
          if (sm.confirm) {
            wx.request({
              url: `${app.globalData.baseUrl}/api/finance/update`,
              method: "POST",
              data: { id: that.data.id, isPlacement: 1 },
              header: {
                "Content-Type": "application/json",
                'token': wx.getStorageSync('token'),
              },
              success: function (res) {
                if (res.data.code == 0) {
                  that.getDepartment(that.data.id);
                } else {
                  wx.showToast({
                    title: res.data.msg || '出错啦！',
                    icon: 'error',
                    duration: 2000
                  })
                }
              },
              fail() {
                wx.showToast({
                  title: '出错啦！',
                  icon: 'error',
                  duration: 2000
                })
              }
            })
          } else {
            console.log('用户点击取消');
          }
        }
      });
    },
});